<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <!--防止css、js资源缓存-->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />

    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta content="telephone=no,email=no" name="format-detection">
    <script type="text/javascript" src="asserts/resource/js/flexible_C.js" ></script>
    <link rel="stylesheet" href="asserts/resource/css/common.css">
    <link rel="stylesheet" href="asserts/resource/css/css.css">
    <title>实时定位</title>
    <style type="text/css">
        body, html,#allmap,#Panorama {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
    </style>
    <script type="text/javascript" src="asserts/resource/js/jquery.min.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=A4LmXLHVeMzGbVYqMvC4i5tiodzwqKn5"></script>
</head>
<body>
<div id="allmap"></div>
<div id="Panorama"></div>
<div id="newFaction">
    <div class="positionIcon">
        <div id="old">
            <p><img src="asserts/resource/img/oldmanS.png"></p>

        </div>
        <div id="phone">
            <p><img src="asserts/resource/img/phoneCirS.png"></p>
        </div>
    </div>
    <div class="around" id="around">
        <a class="distance"></a>
    </div>
    <div class="its-place"></div>
    <div class="navgation" id="navGa"></div>
</div>

<div id="setPanoramaByLocation" class="panoLocation">
    <span>全景</span>
</div>
<div id="panoClose"></div>
</body>
</html>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="asserts/resource/js/js.js"></script>
<script type="text/javascript" src="asserts/resource/js/jquery.min.js"></script>
<script type="text/javascript" src="asserts/resource/layer/mobile/layer.js"></script>
<script type="text/javascript">
    var map = new BMap.Map("allmap");
    var terminalName;//设备昵称
    var oldPersion_point; //老人位置
    var oldPersion_marker=new BMap.Marker();//老人标记
    var oldIcon = new BMap.Icon("asserts/resource/img/imei.png", new BMap.Size(15,30));
    var phoneIcon = new BMap.Icon("asserts/resource/img/self.png", new BMap.Size(15,30));
    var phoneMarker;//手机位置
    var infoLabel=new BMap.Label();
    var sContent=''; //显示信息拼接字符串
    var isShow=true; //是否显示信息框
    var addressValue; //老人位置详细信息
    var gpsPoint;//调用外部导航需要的坐标点


    //获取微信JS-SDK权限验证的签名
    function getJsSdkSign() {

        var url=encodeURIComponent(location.href.split('#')[0]);
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            async: true, // 使用异步方式
            data: {"url":url},
            dataType: "json",//预期服务器返回的数据类型
            url: "/position/getJsApiSign" ,//url
            success: function (result) {
                var data=result.data;
                if (result.status == 1) {
                    wx.config({
                        // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.appId, // 必填，公众号的唯一标识
                        timestamp: data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: data.noncestr, // 必填，生成签名的随机串
                        signature: data.signature,// 必填，签名
                        jsApiList: ['openLocation'] // 必填，需要使用的JS接口列表
                    });
                }else{
                    layerMsg(result.msg,2);
                }
            },
            error : function() {
                layerMsg("网络异常!",2);
            }
        });
    }



    function getData() {
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            async: false, // 使用同步方式
            dataType: "json",//预期服务器返回的数据类型
            url: "/position/realtime" ,//url
            success: function (result) {
                var data=result.data;
                if (result.status == 1) {
                    if(data){
                        map.removeOverlay(oldPersion_marker);
                        terminalName= data.terminalName;
                        oldPersion_point = new BMap.Point(data.longitudeShow,data.latitudeShow);
                        oldPersion_marker.setIcon(oldIcon);  // 设置图标对象
                        oldPersion_marker.setPosition(oldPersion_point); //设置地理位置

                        map.addOverlay(oldPersion_marker);

                        sContent='';
                        //获取点的信息
                        sContent ='<ul class ="markwrap">'
                            +'<p class="Dclose"><a id="Dclose">x</a></p>'
                            +'<li><span>昵称：</span>' + terminalName+ '</li>'
                            +'<li>'+'<span>定位方式：</span>' + data.locationType + '</li>'
                        if(data.locationType=="lbs"){
                            if(data.dumpEnergy){
                                sContent+='<li><span>当前电量：</span>' + data.dumpEnergy +'%'+ '</li>';
                            }
                        }
                        sContent+='<li>' + data.recordTime + '</li></ul>';

                        //判断第一次执行
                        if(isShow){
                            showInfo(oldPersion_marker);
                        }

                        //显示详细地址
                        var geoc = new BMap.Geocoder();

                        geoc.getLocation(oldPersion_point, function (rs) {

                            var addComp = rs.addressComponents;
                            addressValue=addComp.city + addComp.district + rs.business +addComp.street + addComp.streetNumber;
                            //对应的省市区、县街道，街道号
                            $('.its-place').html(terminalName+":"+addressValue)

                        });

                    }
                }else{
                    layerMsg(result.msg,2);
                }
            },
            error : function(XMLHttpRequest,textStatus,errorThrown) {
                // 通过XMLHttpRequest取得响应头，sessionstatus
                var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus");
                // var sessionstatus = repeatlogin
                if(sessionstatus=="timeout"){
                    // 如果session过期就重新登录
                    laSelfMsg("页面过期，请重新登录");
                    clearInterval(interval);
                }else if(sessionstatus=="repeatlogin"){
                    laSelfMsg("您的设备已在其他机器登录，请注意账号安全!");
                    clearInterval(interval);
                }else {
                    layerMsg("网络异常!",2);
                }
            }
        });

        //手机定位
        phoneLocation();
    }

    getJsSdkSign();

    getData();

    if(oldPersion_point){
        //定时查询最新定位信息
        var interval = setInterval(getData, 10000);

        map.centerAndZoom(oldPersion_point,15);

        //百度地图经纬度转换为原google坐标系(gcj02)
        setTimeout(function(){
            var convertor = new BMap.Convertor();
            var pointArr = [];
            pointArr.push(oldPersion_point);
            convertor.translate(pointArr, 5, 3, translateCallback)
        }, 1000);
    }

    //坐标转换完之后的回调函数
    translateCallback = function (data){
        if(data.status === 0) {
            gpsPoint=data.points[0];
        }
    }

    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
    map.disableDoubleClickZoom();
    map.disableInertialDragging();
    // map.disablePinchToZoom();
    map.enablePinchToZoom();
    map.setMinZoom(3);
    map.setMaxZoom(18);



    function phoneLocation() {
        //---手机定位
        var geolocation = new BMap.Geolocation();

        geolocation.getCurrentPosition(function(r){
            map.removeOverlay(phoneMarker);
            if(this.getStatus() == BMAP_STATUS_SUCCESS){

                phonePoint = r.point;

                phoneMarker = new BMap.Marker(r.point,{icon:phoneIcon});

                map.addOverlay(phoneMarker);


                distance();
            }
            else {
                layerMsg('failed'+this.getStatus(),2);
            }
        },{enableHighAccuracy: true})
    }


    //点击红点显示终端信息
    oldPersion_marker.addEventListener("click",function() {

        isShow=true;

        showInfo(oldPersion_marker);

    });

    // 微信导航
    var nav = document.getElementById("navGa");
    nav.addEventListener("click",function(){
        //打开微信内置地图，并使用导航
        wx.ready(function() {
            // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
            wx.openLocation({
                latitude: gpsPoint.lat, // 纬度，浮点数，范围为90 ~ -90
                longitude: gpsPoint.lng, // 经度，浮点数，范围为180 ~ -180。
                address: addressValue,
                scale: 14
            });
        });
        wx.error(function(res) {
            layerMsg(res.errMsg,2);
        });
    })
    //居中当前定位
    var phone = document.getElementById("phone");

    var old = document.getElementById("old");

    old.addEventListener("click",function(){

        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            url: "/position/activePosition"//url
        });

        if(oldPersion_point){
            map.centerAndZoom(oldPersion_point,15);
        }

        distance();
    });

    phone.addEventListener("click",function(){
        map.centerAndZoom(phonePoint,15);
        distance();
    });

    function distance(){

        if(oldPersion_point){
            var mile = map.getDistance(phonePoint,oldPersion_point).toFixed(0);

            if( mile <= 100 && mile >= 0){

                $('.distance'). html('100米以内');

            }
            else if( mile > 100 && mile <=1000){

                $('.distance'). html('相距约：'+mile+'米');

            }
            else{
                $('.distance'). html('相距约：'+parseInt(mile/1000)+'千米');
            }
        }else{
            map.centerAndZoom(phonePoint,15);
            $('.distance'). html('暂无定位数据');
        }
    };

    function showInfo(marker) {

        infoLabel.setContent(sContent);  // 创建文本标注对象

        infoLabel.setStyle({
            position:"relative",
            color : "#ffffff",
            fontSize : ".33rem",
            minWidth:"3.5rem",
            border:"none",
            background:"linear-gradient(rgba(51,51,51,.7), rgba(0,0,0,.7),rgba(51,51,51,.7))",
            borderRadius: "10px",
            boxShadow:"5px 5px 5px #868686",
            padding:".1rem",
            display:"none"
        });

        marker.setLabel(infoLabel);

        setTimeout(function() {

            LabW = $($(".BMapLabel")[1]).width();

            labH = $($(".BMapLabel")[1]).height();

            closelable(LabW,labH);
        },1000)

    };

    function closelable(LabW,labH){

        infoLabel.setOffset(new BMap.Size(-parseInt(LabW / 2 + 2), -parseInt(labH + 20)));

        infoLabel.setStyle({display: "inline-block"});

        var Dc = document.querySelectorAll("#Dclose");
        if( Dc[0]){
            Dc[0].addEventListener("touchstart",function() {

                isShow=false;

                infoLabel.setStyle({display:"none"});

            });
        }
    };

    //显示街景
    document.getElementById("setPanoramaByLocation").onclick = function(){

        var panorama = new BMap.Panorama('Panorama');

        panorama.setPov({heading: -40, pitch: 6});//根据经纬度坐标展示全景图 heading标题-40像素 pitch倾斜6像素

        panorama.setPosition(oldPersion_point); //根据经纬度坐标展示全景图

        var panoramaService = new BMap.PanoramaService();
        panoramaService.getPanoramaByLocation(oldPersion_point, function(data) {
            if (!data) {
                $("#Panorama").html("<h1 class='nullMap'>暂无街景图...</h1>");
                return;
            }

        })
        //地图
        $("#allmap").hide();

        $("#newFaction").hide();
        //街景
        $("#Panorama").show();

        $("#panoClose").show();

        $("#setPanoramaByLocation").hide();
    };

    $("#panoClose").on("click",function(){
        //街景
        $(this).hide();

        $("#Panorama").hide();

        $("#setPanoramaByLocation").show();

        $("#Panorama").html("");
        //地图
        $("#allmap").show();

        $("#newFaction").show();
    })
    //---------添加地图类型控件-----------
    var MapTypeControl = new BMap.MapTypeControl({
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ],
        offset : new BMap.Size(10,50)
    });
    map.addControl(MapTypeControl);

    // ---------定义缩放控件  -----------
    function ZoomControl() {
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
        this.defaultOffset = new BMap.Size(10, 100);
    }
    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMap.Control();

    // 自定义控件必须实现initialize方法，并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    ZoomControl.prototype.initialize = function (map) {
        //+-包裹层
        var mapwrap = document.createElement("div");
        mapwrap.className = 'zoomwrap';
        //创建一个放大img
        var plus_div = document.createElement("div");
        plus_div.className = 'plusDiv';
        var map_p_lus = document.createElement("p");
        map_p_lus.className = 'plus';
        var map_plus = document.createElement("img");
        map_plus.setAttribute("src", "asserts/resource/img/plus.png");

        //为img设置点击事件
        map_plus.onclick = function () {
            map.zoomIn();
        }
        //创建一个缩小img
        var minus_div = document.createElement("div");
        minus_div.className = 'minusDiv';
        var map_m_inus = document.createElement("p");
        map_m_inus.className = 'minus';
        var img_minus = document.createElement("img");
        img_minus.setAttribute("src", "asserts/resource/img/minus.png");
        img_minus.onclick = function () {
            map.zoomOut();
        }
        //添加放大的img图标到div中
        mapwrap.appendChild(plus_div);
        plus_div.appendChild(map_p_lus);
        map_p_lus.appendChild(map_plus);
        //添加缩小的img图标到div中
        mapwrap.appendChild(minus_div);
        minus_div.appendChild(map_m_inus);
        map_m_inus.appendChild(img_minus);
        //添加DOM元素到地图中
        map.getContainer().appendChild(mapwrap);
        //将DOM元素返回;
        return mapwrap;
    }

    // 创建控件实例
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);

</script>